/* eslint-disable no-shadow */
import React, { Component } from 'react';
import { Icon, Radio, Button, message, Upload } from 'antd';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import PropTypes from 'prop-types';
import * as qiniu from 'qiniu-js';
import { QINIU_DOMAIN } from '../../../utils/constants';

import API from '../../../api/account/index';
import TokenAPI from '../../../api/auth/index';

import './AccountSetting.scss';

const classNames = require('classnames');

const RadioGroup = Radio.Group;

class AccountSetting extends Component {
  state = {
    account: JSON.parse(window.sessionStorage.getItem('account')),
    avatar: '',
    editSexVisible: false,
    saveButtonVisible: false,
  };
  handleCopy() {
    message.success('复制成功');
  }
  handleChangeSex = (e) => {
    const sex = e.target.value;
    const { account } = this.state;
    account.sex = sex;
    this.setState({
      account,
    });
  };
  editSex = () => {
    const { editSexVisible } = this.state;
    this.setState({
      editSexVisible: !editSexVisible,
    });
  };
  saveSex = async () => {
    const { sex } = this.state.account;
    const tmp = sex;
    const response = await API.modifyAccount({ sex });
    const { code } = response;
    if (code === 1) {
      message.success('修改成功');
      const { account } = this.state;
      account.sex = tmp;
      window.sessionStorage.setItem('account', JSON.stringify(account));
      this.setState({
        editSexVisible: false,
      });
    } else {
      // message.error('修改失败');
    }
  };
  handleUpload = async ({ file }) => {
    const response = await TokenAPI.getUploadToken();
    const { code, data } = response;
    if (code === 1) {
      const token = data;
      const config = {
        useCdnDomain: true,
      };
      const putExtra = {
        fname: '',
        params: {},
        mimeType: null,
      };
      const complete = async (res) => {
        const url = `${QINIU_DOMAIN}/${res.key}`;
        const response = await TokenAPI.getDownloadUrl(url);
        const { code, data } = response;
        if (code === 1) {
          this.setState({
            avatar: url,
            saveButtonVisible: true,
          });
          const { account } = this.state;
          account.avatar = data;
          window.sessionStorage.setItem('account', JSON.stringify(account));
          account.avatar = `${account.avatar}&imageView2/1/w/80/h/80`;
          this.setState({ account });
        }
      };

      //  let subscription;
      // 调用sdk上传接口获得相应的observable，控制上传和暂停
      const observable = qiniu.upload(file, null, token, putExtra, config);
      observable.subscribe(undefined, undefined, complete);
    } else {
      // message.error('token获取失败');
    }
  };
  // handleChange = (file, fileList, event) => {
  //   console.log(file);
  // };
  saveAvatar = async (e) => {
    e.stopPropagation();
    const { avatar } = this.state;
    const response = await API.modifyAccount({ avatar });
    const { code } = response;
    if (code === 1) {
      message.success('修改成功');
    }
  }
  render() {
    const { account } = this.state;
    // const avatar = `${account.avatar}&imageView2/1/w/50/h/50`
    const lengthOfdepartments = account.department.length;
    return (
      <main>
        <div className="content-title">个人资料设置</div>
        <div className="detail">
          <div className="left">
            <Upload
              name="avatar"
              className="avatar-uploader"
              showUploadList={false}
              customRequest={this.handleUpload}
              // onChange={this.handleChange}
            >
              <img src={account.avatar} alt="avatar" />
              {
                this.state.saveButtonVisible ?
                  <span className="upload-confirm">
                    <Icon
                      type="check-circle-o"
                      style={{ fontSize: 36, color: '#3ecf7b', marginRight: 10 }}
                    />
                    <span role="button" tabIndex="0" style={{ display: 'block', lineHeight: '36px' }} onClick={this.saveAvatar}>点击保存</span>
                  </span> :
                  <span className="upload-select">
                    <Icon type="camera" style={{ fontSize: 36 }} />
                  </span>
              }
            </Upload>
            <span style={{ marginTop: 10 }}>{account.nickname}</span>
            <br />
            {/* <input className="file-input" type="file" id="select" /> */}
          </div>
          <div className="right">
            <div className="row">
              <div className="row--label">昵称：</div>
              <div className="row--content">{account.fullname}</div>
            </div>
            <div className="row">
              <div className="row--label">性别：</div>
              {this.state.editSexVisible ? (
                <div className="row--content">
                  <span className="row--edit">
                    <RadioGroup
                      onChange={this.handleChangeSex}
                      value={account.sex}
                    >
                      <Radio value="male">男</Radio>
                      <Radio value="female">女</Radio>
                    </RadioGroup>
                  </span>
                  <Button type="primary" onClick={this.saveSex}>
                    保存
                  </Button>
                </div>
              ) : (
                <div className="row--content">
                  {account.sex === 'male' ? '男' : '女'}{' '}
                  <Icon onClick={this.editSex} type="edit" />{' '}
                </div>
              )}
            </div>
            <div className="row">
              <div className="row--label">
                部门<span style={{ margin: '0 1px' }}>|</span>职位：
              </div>
              <div className="row--content">
                {account.department.map((item, index) => {
                  const classNameOfSpan = classNames({
                    hide: index === lengthOfdepartments - 1,
                  });
                  return (
                    <span key={Math.random()}>
                      {item.nickname}
                      <span className={classNameOfSpan}> &gt; </span>
                    </span>
                  );
                })}
                <span style={{ margin: '0 4px' }}>|</span>
                {account.company.title}
              </div>
            </div>
            <div className="row">
              <div className="row--label">邮箱：</div>
              <div className="row--content">{account.email.address}</div>
            </div>
            <div className="row">
              <div className="row--label">手机号：</div>
              <div className="row--content">{account.tel.number}</div>
            </div>
            <div className="row">
              <div className="row--label">微信号：</div>
              <div className="row--content">{account.wechat.nickname}</div>
            </div>
            <div className="row">
              <div className="row--label">AccessKey：</div>
              <div className="row--content">
                {account.accessKey}
                <CopyToClipboard
                  onCopy={this.handleCopy}
                  text={account.accessKey}
                >
                  <Icon type="copy" />
                </CopyToClipboard>
              </div>
            </div>
            <div className="row">
              <div className="row--label">密码：</div>
              <div className="row--content">
                ******{' '}
                <Icon type="edit" onClick={this.props.togglePasswordEdit} />
              </div>
            </div>
          </div>
        </div>
      </main>
    );
  }
}

AccountSetting.propTypes = {
  togglePasswordEdit: PropTypes.func.isRequired,
};

export default AccountSetting;
